import router from '@system.router';
import prompt from '@system.prompt';
import * as wordService from '../../common/wordService.js';
import * as syncService from '../../common/syncService.js';
import * as api from '../../common/api.js';

export default {
    data: {
        isLoading: true,
        isReviewMode: false,  // 是否为复习模式
        currentWord: null,    // 当前单词
        words: [],           // 所有单词
        currentIndex: 0,      // 当前索引
        totalWords: 0,        // 总单词数
        showAnswer: false,    // 是否显示答案
        isCompleted: false,   // 是否完成学习
        correctCount: 0,      // 正确数量
        wrongCount: 0,        // 错误数量
        progressText: '准备学习...',
        progressPercent: 0,
        extraNewWords: 0,     // 额外新词数量
        extraReviewWords: 0   // 额外复习词数量
    },
    
    onInit() {
        // 从路由参数获取模式和额外单词数量
        const params = router.getParams();
        this.isReviewMode = params.isReviewMode === 'true' || false;
        this.extraNewWords = parseInt(params.extraNewWords || '0', 10);
        this.extraReviewWords = parseInt(params.extraReviewWords || '0', 10);
        
        // 加载单词
        this.loadWords();
    },
    
    async loadWords() {
        try {
            this.isLoading = true;
            this.progressText = '正在获取单词...';
            
            // 使用单词服务获取每日单词
            const result = await wordService.getDailyStudyWords(
                this.extraNewWords, 
                this.extraReviewWords
            );
            
            if (this.isReviewMode) {
                // 复习模式获取复习单词
                this.words = result.reviewWords || [];
                this.progressText = '复习模式';
            } else {
                // 学习模式获取新单词
                this.words = result.newWords || [];
                this.progressText = '学习模式';
            }
            
            this.totalWords = this.words.length;
            
            if (this.totalWords > 0) {
                this.currentWord = this.words[0];
                this.updateProgress();
            } else {
                // 没有需要学习的单词
                this.progressText = this.isReviewMode ? '没有复习单词' : '没有新单词';
                this.isCompleted = true;
            }
        } catch (error) {
            console.error('加载单词失败:', error);
            prompt.showToast({
                message: '加载单词失败，请检查网络连接',
                duration: 2000
            });
        } finally {
            this.isLoading = false;
        }
    },
    
    // 处理用户认识单词
    async handleKnown() {
        if (!this.currentWord) return;
        
        this.correctCount++;
        this.showAnswer = true;
        
        try {
            // 记录学习情况
            const studyResult = await wordService.recordWordStudy(
                this.currentWord.id,
                true,  // 正确
                !this.isReviewMode  // 是否为新词
            );
            
            // 更新单词掌握度
            if (studyResult.success) {
                this.currentWord.masteryLevel = studyResult.masteryLevel || 0;
            } else {
                // 即使API调用失败，也添加到待同步队列
                await syncService.addPendingSyncRecord(
                    this.currentWord.id,
                    true,
                    !this.isReviewMode
                );
            }
        } catch (error) {
            console.error('记录学习情况失败:', error);
            
            // 添加到待同步队列
            await syncService.addPendingSyncRecord(
                this.currentWord.id,
                true,
                !this.isReviewMode
            );
        }
    },
    
    // 处理用户不认识单词
    async handleUnknown() {
        if (!this.currentWord) return;
        
        this.wrongCount++;
        this.showAnswer = true;
        
        try {
            // 记录学习情况
            const studyResult = await wordService.recordWordStudy(
                this.currentWord.id,
                false,  // 错误
                !this.isReviewMode  // 是否为新词
            );
            
            // 更新单词掌握度
            if (studyResult.success) {
                this.currentWord.masteryLevel = studyResult.masteryLevel || 0;
            } else {
                // 即使API调用失败，也添加到待同步队列
                await syncService.addPendingSyncRecord(
                    this.currentWord.id,
                    false,
                    !this.isReviewMode
                );
            }
        } catch (error) {
            console.error('记录学习情况失败:', error);
            
            // 添加到待同步队列
            await syncService.addPendingSyncRecord(
                this.currentWord.id,
                false,
                !this.isReviewMode
            );
        }
    },
    
    // 显示单词释义
    showMeaning() {
        this.showAnswer = true;
    },
    
    // 下一个单词
    nextWord() {
        if (this.currentIndex < this.totalWords - 1) {
            this.currentIndex++;
            this.currentWord = this.words[this.currentIndex];
            this.showAnswer = false;
            this.updateProgress();
        } else {
            // 学习完成
            this.completeStudy();
        }
    },
    
    // 完成学习
    completeStudy() {
        this.isCompleted = true;
        this.progressText = '学习完成';
        this.progressPercent = 100;
    },
    
    // 更新进度
    updateProgress() {
        if (this.totalWords > 0) {
            this.progressPercent = Math.floor(((this.currentIndex + 1) / this.totalWords) * 100);
            this.progressText = `进度: ${this.progressPercent}%`;
        } else {
            this.progressPercent = 0;
            this.progressText = '无单词';
        }
    },
    
    // 获取正确率
    get correctRate() {
        const total = this.correctCount + this.wrongCount;
        if (total === 0) return 0;
        return Math.round((this.correctCount / total) * 100);
    },
    
    // 获取难度文字描述
    getDifficultyText(difficulty) {
        switch (difficulty) {
            case 1: return '简单';
            case 2: return '较易';
            case 3: return '中等';
            case 4: return '较难';
            case 5: return '困难';
            default: return '未知';
        }
    },
    
    // 返回主页
    backToHome() {
        router.replace({
            uri: '../index/index'
        });
    },
    
    // 同步数据
    async syncData() {
        try {
            prompt.showToast({
                message: '正在同步数据...',
                duration: 2000
            });
            
            const syncResult = await syncService.syncWithPhone();
            
            if (syncResult.success) {
                prompt.showToast({
                    message: `同步成功！新词:${syncResult.newWordsCount}，复习:${syncResult.reviewWordsCount}`,
                    duration: 3000
                });
            } else {
                prompt.showToast({
                    message: '同步失败：' + (syncResult.message || '未知错误'),
                    duration: 3000
                });
            }
        } catch (error) {
            console.error('同步数据失败:', error);
            prompt.showToast({
                message: '同步数据失败，请稍后重试',
                duration: 2000
            });
        }
    }
}; 